<template>
  <section>
    <div class="section-header">甲方负责人报工</div>
    <a-row :gutter="24">
      <a-col :span="8">
        <a-form-model-item label="节点报工：" prop="status">
          <div style="display: flex" class="col-input-2">
            <a-select v-model="task.partaStatus" @change="changeStatus">
              <a-select-option
                v-for="(code, index) in codes.WorkReportResultStatus"
                :key="'status' + index"
                :value="code.code"
              >
                {{ code.name }}
              </a-select-option>
            </a-select>
            <a-select v-model="task.partaResult">
              <a-select-option
                v-for="(code, index) in codes.WorkReportResultTypeFilter"
                :key="'result' + index"
                :value="code.code"
              >
                {{ code.name }}
              </a-select-option>
            </a-select>
          </div>
        </a-form-model-item>
      </a-col>
      <a-col :span="8">
        <a-form-model-item ref="actualTime" label="实际完成日期：" prop="actualTime">
          <a-date-picker
            valueFormat="YYYY-MM-DD"
            v-model="task.partaActualTime"
            clearable
            :disabled-date="disabledActualTimeDate"
          />
        </a-form-model-item>
      </a-col>
      <a-col :span="8">
        <a-form-model-item ref="planTime" label="预计完成日期：" prop="planTime">
          <a-date-picker
            valueFormat="YYYY-MM-DD"
            v-model="task.partaPlanTime"
            clearable
            :disabled-date="disabledPlanTimeDate"
          />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="8">
        <a-form-model-item label="工期状态：" prop="nodeStatus">
          <div style="display: flex">
            <a-select disabled v-model="task.partaNodeStatus">
              <a-select-option
                v-for="(code, index) in codes.WorkReportNodeStatus"
                :key="'nodeStatus' + index"
                :value="code.code"
              >
                {{ code.name }}
              </a-select-option>
            </a-select>
            <a-input
              class="widthFull"
              style="width: 10vw; margin-left: 5px"
              v-if="task.partaNodeStatus == '逾期'"
              disabled
              v-model="task.partaNodeDelayDays"
              suffix="天"
            />
          </div>
        </a-form-model-item>
      </a-col>
      <a-col :span="8">
        <a-form-model-item ref="delayReason" label="逾期责任方：" prop="delayReason">
          <div style="display: flex" class="diyClass">
            <a-select
              v-model="task.partaDelayReason"
              :disabled="!checkPermission(['WORK_REPORT_MANAGER', '合同报工员']) && task.partaNodeStatus != '逾期'"
              allowClear
              @change="changeDelayReason"
            >
              <a-select-option
                v-for="(code, index) in codes.WorkReportDelayReson"
                :key="'delayReason' + index"
                :value="code.code"
              >
                {{ code.name }}
              </a-select-option>
            </a-select>
            <a-input
              v-if="task.partaDelayReason == '2'"
              v-model="task.partaDelayDays"
              addonBefore="甲方逾期"
              addonAfter="天"
            />
          </div>
        </a-form-model-item>
      </a-col>
      <a-col :span="8">
        <a-form-model-item ref="delayRemark" label="逾期具体原因：" prop="delayRemark">
          <a-select
            v-model="task.partaDelayRemark"
            :disabled="!checkPermission(['WORK_REPORT_MANAGER', '合同报工员']) && task.partaNodeStatus != '逾期'"
            allowClear
          >
            <a-select-option
              v-for="(code, index) in codes.WorkReportDelayRemarkFilter"
              :key="'delayRemark' + index"
              :value="code.code"
            >
              {{ code.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="8">
        <a-form-model-item label="现场验收日期：" prop="acceptTime">
          <a-date-picker
            valueFormat="YYYY-MM-DD"
            v-model="task.partaAcceptTime"
            :disabled-date="disabledAcceptTimeDate"
          />
        </a-form-model-item>
      </a-col>
      <a-col :span="8">
        <a-form-model-item label="基建造价员：" prop="budgetingUser">
          <UserInputSelector
            :username.sync="task.partaBudgetingUserId"
            :realname.sync="task.partaBudgetingUser"
            multiple="default"
            placeholder="请选择"
          />
        </a-form-model-item>
      </a-col>
      <a-col :span="8">
        <a-form-model-item label="甲方报工日期：" prop="reportDate">
          <a-date-picker disabled style="width: 100%" valueFormat="YYYY-MM-DD" v-model="task.partaReportDate" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="24">
        <a-form-model-item label="补充说明：" prop="remark">
          <a-input v-model="task.partaRemark" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <div class="section-table">
      <div style="display: flex">
        <ht-upload
          v-if="checkPermission(['WORK_REPORT_MANAGER'])"
          ref="myUpload"
          class="upload-demo"
          dbKey="Trd"
          busField="workReport"
          busType="work_report_attach_a"
          ftpKey="ftp"
          v-model="fileList"
          :show-file-list="false"
          :before-upload="beforUpload"
          :on-success="afterUpload"
        >
          <a-button class="hte-btn add-btn" type="primary" icon="plus">新增附件</a-button>
        </ht-upload>
        <a-button @click="handleDownload()"> 下载 </a-button>
        <a-button @click="removeAttachRow()"> 删除 </a-button>
        <a-button
          type="link"
          @click="downloadResultTemplate('2638e2760dac407292c47a71b1e26d53', '合同验收表（非基建）.docx')"
        >
          合同验收表（非基建）.docx
        </a-button>
        <a-button
          type="link"
          @click="downloadResultTemplate('a30b4e36c7fc42a0804e693202c53ffd', '工程项目验收表（基建类工程）.doc')"
        >
          工程项目验收表（基建类工程）.doc
        </a-button>
      </div>
      <div>
        <a-table
          class="hte-table-content"
          :columns="columns"
          :data-source="attachs"
          :pagination="false"
          size="middle"
          rowKey="randomStr"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >
          <span slot="action" slot-scope="text, record,index" style="display: flex">
            <a-button
              v-if="checkPermission(['WORK_REPORT_MANAGER'])"
              type="primary"
              size="small"
              @click="removeAttachRowByOne(record,index)"
              >删除</a-button
            >
          </span>
          <span slot="createTimeRender" slot-scope="text, record">
            <span v-if="record.createTime && record.createTime != '1900-01-01 00:00:00'">
              {{ record.createTime }}
            </span>
          </span>
          <span slot="index" slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span slot="previewRender" slot-scope="text, record">
            <span class="font-active" @click="handlePreview(record)">
              {{ record.fileName }}
            </span>
          </span>
        </a-table>
      </div>
    </div>
  </section>
</template>

<script>
import Vue from 'vue'
import { getAction, postAction } from '@/api/manage'
import { formatFileSize, endWith } from '@/utils/common.js'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { calcDaysBetween } from '@/utils/util.js'
import '@/config/upload.install.js'
import { now } from 'moment'
export default {
  components: {},
  props: {
    task: {
      type: Object,
      default: () => {
        return {}
      },
    },
    complateTime: {
      type: Date,
      default: null,
    },
  },
  data() {
    return {
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'index' },
        },
        {
          title: '文件名称',
          dataIndex: 'fileName',
          key: 'fileName',
          scopedSlots: { customRender: 'previewRender' },
        },
        {
          title: '文件大小',
          dataIndex: 'fileSize',
          key: 'fileSize',
        },
        {
          title: '上传人',
          dataIndex: 'createUser',
          key: 'createUser',
        },
        {
          title: '上传时间',
          dataIndex: 'createTime',
          key: 'createTime',
          scopedSlots: { customRender: 'createTimeRender' },
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'action' },
        },
      ],
      attachs: [],
      fileList: [],
      urls: {
        codes: '/manage/codeInfo/queryByTypes',
      },
      index: {},
      showUserSelector: false,
      codes: { WorkReportDelayRemarkFilter: [] },
      currentSelection: [],
      selectedRowKeys: [],
    }
  },
  mounted() {
    this.fetchCodes()
  },
  methods: {
    calcDaysBetween,
    disabledActualTimeDate(actualTime) {
      if (!actualTime) {
        return false
      }
      return actualTime.valueOf() >= new Date().valueOf()
    },
    disabledPlanTimeDate(planTime) {
      if (!planTime) {
        return false
      }
      return planTime.valueOf() < new Date().valueOf()
    },
    disabledAcceptTimeDate(acceptTime) {
      if (!acceptTime) {
        return false
      }
      return acceptTime.valueOf() >= new Date().valueOf()
    },
    checkPermission(powers) {
      let hasPower = true
      return hasPower
    },
    fetchCodes() {
      getAction(this.urls.codes, {
        types:
          'WorkReportResultType,WorkReportResultStatus,WorkReportDelayReson,WorkReportNodeStatus,WorkReportDelayRemark',
      }).then((res) => {
        if (res.success) {
          this.codes = { ...this.codes, ...res.result }
          this.$set(this.codes, 'WorkReportDelayRemarkFilter', this.codes.WorkReportDelayRemark)
          this.$set(this.codes, 'WorkReportResultTypeFilter', this.codes.WorkReportResultType)
          this.changeDelayReason()
        }
      })
    },
    addAttachRow() {
      this.attachs.push({ id: 0, busKey: '' })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.currentSelection = selectedRows
    },
    removeAttachRow() {
      let record = this.currentSelection[0]
      if (this.currentSelection.length <= 0) {
        return this.$messageWorkReport.warning('请至少选择一个记录操作')
      }
      let ids = []
      this.currentSelection.forEach((s) => {
        if (s.id) {
          ids.push(s.id)
        }
      })
      if (ids.length <= 0) {
        return this.$messageWorkReport.warning('未找到附件记录')
      }
      if (ids.length > 0) {
        postAction(this.urls.deleteBetch + '?ids=' + ids.join(','), {}).then((res) => {
          if (res.success) {
            this.fetchAttach()
          } else {
            this.$messageWorkReport.error(res.message)
          }
        })
      }
    },
    removeAttachRowByOne(record,index) {
      if (record.id) {
        postAction(this.urls.deleteBetch + '?ids=' + record.id, {}).then((res) => {
          if (res.success) {
            this.fetchAttach()
          } else {
            this.$messageWorkReport.error(res.message)
          }
        })
      } else {
        this.attachs = this.attachs.splice(index,1)
      }
    },
    clearAttach(index) {
      let record = this.attachs[index]
      if (record.id) {
        postAction(this.urls.clearAttach + '/' + record.id, {}).then((res) => {
          if (res.success) {
            this.fetchAttach()
          } else {
            this.$messageWorkReport.error(res.message)
          }
        })
      }
    },
    handleDownload() {
      if (this.currentSelection.length == 1) {
        let record = this.currentSelection[0]
        if (record.busFk) {
          const token = Vue.ls.get(ACCESS_TOKEN)
          let url =
            process.env.VUE_APP_API_BASE_URL + '/workReport/attach/download?token=' + token + '&id=' + record.busFk
          if (record.platForm == 'CLOUD') {
            url =
              process.env.VUE_APP_PS_API_BASE_URL +
              '/hte/contract/downloadUnion?&id=' +
              record.busFk +
              '&platForm=CLOUD' +
              '&fileName=' +
              record.fileName
          }
          if (record.platForm == 'CLOUDFOLDER') {
            url =
              process.env.VUE_APP_PS_API_BASE_URL +
              '/hte/contract/downloadUnion&id=' +
              record.busFk +
              '&platForm=CLOUDFOLDER' +
              '&fileName=' +
              record.fileName
          }
          window.open(url)
        }
      } else if (this.currentSelection.length > 1) {
        let newIds = []
        this.currentSelection.forEach((r) => {
          newIds.push(r.busFk + '_' + r.platForm + '_' + r.fileName)
        })
        const token = Vue.ls.get(ACCESS_TOKEN)
        let url =
          process.env.VUE_APP_API_BASE_URL +
          '/workReport/attach/downloadUnionZip?token=' +
          token +
          '&ids=' +
          newIds.join(',')
        window.open(url)
      }
    },
    handlePreview(file) {
      let that = this
      if (
        endWith(file.fileName, 'rar') ||
        endWith(file.fileName, 'zip') ||
        endWith(file.fileName, 'dwg') ||
        endWith(file.fileName, 'tgz')
      ) {
        return true
      }
      let token = Vue.ls.get(ACCESS_TOKEN)
      let url =
        process.env.VUE_APP_API_BASE_URL + '/common/previewAttach?token=' + token + '&id=' + file.busFk + '&ftpKey=ftp'
      if (file.platForm == 'CLOUD') {
        url =
          process.env.VUE_APP_PS_API_BASE_URL +
          '/hte/contract/previewAttachUnion?id=' +
          file.busFk +
          '&ftpKey=ftp' +
          '&fileName=' +
          file.fileName +
          '&platForm=' +
          file.platForm
      }
      if (file.platForm == 'CLOUDFOLDER') {
        url =
          process.env.VUE_APP_PS_API_BASE_URL +
          '/hte/contract/previewAttachUnion?id=' +
          file.busFk +
          '&ftpKey=ftp' +
          '&fileName=' +
          file.fileName +
          '&platForm=' +
          file.platForm
      }
      window.open(process.env.BASE_URL + '/pdf/web/viewer.html?file=' + encodeURIComponent(url))
    },
    beforUpload(index) {
      this.index = index
    },
    afterUpload(response) {
      let record = {} //this.attachs[this.index]
      if (response && response.length > 0) {
        this.$set(record, 'fileName', response[0].fileName)
        this.$set(record, 'filePath', response[0].path)
        this.$set(record, 'fileSize', response[0].size)
        this.$set(record, 'createUser', response[0].uploaderName)
        this.$set(record, 'createUserId', response[0].uploader)
        this.$set(record, 'createTime', response[0].uploadTime)
        this.$set(record, 'busType', response[0].busType)
        this.$set(record, 'busKey', '')
        this.$set(record, 'busFk', response[0].id)
        this.$set(record, 'platForm', 'HTE')
        this.attachs.push(record)
        this.randomString(10)
      }
    },
    getResult() {
      this.$set(this.task, 'partaAttachs', this.attachs)
      return this.task
    },
    changeDelayReason() {
      let delayRemark = ''
      if (this.codes.WorkReportDelayRemark) {
        this.codes.WorkReportDelayRemark.forEach((item) => {
          if (item.code == this.task.partaDelayRemark) {
            delayRemark = item.name
          }
        })
      }

      let delayReson = ''
      if (this.codes.WorkReportDelayReson) {
        this.codes.WorkReportDelayReson.forEach((item) => {
          if (item.code == this.task.partaDelayReason) {
            delayReson = item.name
          }
        })
      }
      let WorkReportDelayRemarkFilter = []
      if (this.codes.WorkReportDelayRemark) {
        this.codes.WorkReportDelayRemark.forEach((item) => {
          if (item.name.startsWith(delayReson)) {
            WorkReportDelayRemarkFilter.push(item)
          }
        })
      }
      this.$set(this.codes, 'WorkReportDelayRemarkFilter', WorkReportDelayRemarkFilter)
      if (this.task.partaDelayRemark && !delayRemark.startsWith(delayReson)) {
        this.$set(this.task, 'delayRemark', '')
      } else {
        return
      }
    },
    changeStatus() {
      let WorkReportResultTypeFilter = []
      if (this.task.partaStatus != '2') {
        if (this.task.partaResult == '质量合格') {
          this.$set(this.task, 'result', '')
        }
        this.codes.WorkReportResultType.forEach((code) => {
          if (code.name != '质量合格') {
            WorkReportResultTypeFilter.push(code)
          }
        })
        this.$set(this.codes, 'WorkReportResultTypeFilter', WorkReportResultTypeFilter)
      } else {
        this.$set(this.codes, 'WorkReportResultTypeFilter', this.codes.WorkReportResultType)
      }
    },
    randomString(len) {
      if (!this.attachs) {
        this.attachs = []
        return
      }
      this.attachs.forEach((t) => {
        if (!t.randomStr) {
          len = len || 32
          var $chars =
            'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
          var maxPos = $chars.length
          var pwd = ''
          for (let i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
          }
          t.randomStr = pwd
        }
      })
    },
    downloadResultTemplate(id, fileName) {
      let url =
        process.env.VUE_APP_API_BASE_URL +
        '/ps/workReport/downloadResultTemplate?id=' +
        id +
        '&taskId=' +
        this.taskId +
        '&fileName=' +
        fileName +
        '&userName=' +
        this.$store.getters.userInfo.realname
      window.open(url)
    },
    getAttachs() {
      return this.attachs
    },
  },
  watch: {
    task: {
      handler(newV, oldV) {
        let endTime = new Date()
        if (this.task.partaStatus == '2') {
          endTime = this.task.partaActualTime ? this.task.partaActualTime + ' 23:59:59.999' : ''
        }
        let temp = this.calcDaysBetween(this.task.complateTime + ' 23:59:59.999', endTime)
        this.$set(this.task, 'partaNodeStatus', temp.status)
        if (temp.status != '正常') {
          this.$set(this.task, 'partaNodeDelayDays', temp.days)
        } else {
          this.$set(this.task, 'partaNodeDelayDays', 0)
        }
        if(this.task.partaNodeStatus=="正常"){
          this.$set(this.task, 'partaDelayReason', "")
          this.$set(this.task, 'partaDelayRemark', "")
        }
        if(!this.attachs && this.task.partaAttachs){
          this.attachs = this.task.partaAttachs
        }else{
          this.attachs = []
        }
      },
      deep: true,
      immediate: true,
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
section .section-header {
  font-size: 16px;
  font-weight: bold;
  position: relative;
  padding-left: 14px;
  color: #333333;
  margin-bottom: 14px;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-pack: justify;
  justify-content: space-between;
  -ms-flex-align: center;
  align-items: center;
  margin-bottom: 18px;
}

.col-input-2 {
  /deep/ .ant-select:first-child {
    margin-right: 5px;
  }
}
.section-table {
  margin-top: 30px;
  .add-btn {
    margin-left: 0;
    margin-bottom: 10px;
  }
  /deep/ .el-upload__input {
    display: none !important;
  }
}
.redText {
  color: red !important;
}
.diyClass /deep/.ant-input {
  padding: 0 3px;
}
.diyClass /deep/.ant-input-group-addon {
  padding: 0 3px;
}
.widthFull /deep/.ant-input {
  width: 100%;
}
</style>
